package org.graffitidiary.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;
import org.graffitidiary.bean.Brush;
import org.graffitidiary.bean.PathXY;
import org.graffitidiary.utils.GloableParams;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

public class SecondSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{

    /**
     * 是否处于绘制状态
     */
    private boolean mIsDrawing;
    /**
     * 帮助类
     */
    private SurfaceHolder mHolder;

    //保存之前画的路径
    private Bitmap mBitmap;

    /**
     * 画布
     */
    private Canvas mCanvas;
    /**
     * 路径
     */
    private Path mPath;
    /**
     * 画笔
     */
    private Paint mPaint;

    public SecondSurfaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(Color.BLACK, 5);
        initCanvas();
    }

    public SecondSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(Color.BLACK, 5);
        initCanvas();
    }

    public SecondSurfaceView(Context context) {
        super(context);
        initView(Color.BLACK, 5);
        initCanvas();
    }

    private List<Brush> brushs = new ArrayList<Brush>();
    private List<PathXY> list = new ArrayList<PathXY>();

    /**
     * 变换画笔颜色和设置画笔样式
     * @param color
     */
    private void initView(int color, float StrokeWidth) {

        // 创建画笔
        mPaint = new Paint();
        // 画笔颜色
        mPaint.setColor(color);
        // 画笔粗细
        mPaint.setStrokeWidth(StrokeWidth);
        // 抗锯齿
        mPaint.setAntiAlias(true);
        // 描边，不填充
        mPaint.setStyle(Paint.Style.STROKE);
        // 设置外边缘
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        // 形状
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    public void run() {
        long start =System.currentTimeMillis();
        while(mIsDrawing){
            onDraw(mCanvas);
        }
        long end =System.currentTimeMillis();
        if (end-start<100) {
            try {
                Thread.sleep(100-(end-start));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {


    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0) {
        mIsDrawing=true;
        new Thread(this).start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        mIsDrawing=false;
    }

    /**
     * 清除内容
     */
    public void clean(){
        initView(Color.BLACK, 5);
    }

    /**
     * 自动绘制
     */

    Thread thread = null;
    public void autoDraw(List<Brush> brushs){
        this.brushs = brushs;
        thread = new Thread(runnable);
        if(!thread.isAlive()){
            if(null != thread){
                thread.start();
            }
        }
    }

    /**
     * 自动绘制暂停
     */
    public void pause(){
        suspended = true;
    }

    /**
     * 自动绘制继续
     */
    public void ct(){
        suspended = false;
    }

    boolean suspended=false;

    /**
     * 重新绘制之前的东西
     * 暂停
     * 继续
     */
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mCanvas.drawBitmap(mBitmap, 0, 0, mPaint);
            for (int i = 0; i < brushs.size(); i++) {
                int ys = brushs.get(i).getColor();
                float cx = brushs.get(i).getStrokeWidth() * width;
                initView(ys, cx);
                list = new ArrayList<PathXY>();
                list = brushs.get(i).getPathXY();
                mPath = new Path();
                for (int j = 0; j < list.size(); j++) {
                    if(j == 0){
                        touch_start(list.get(j).getX()*width, list.get(j).getY()*height);
                    }
                    touch_move(list.get(j).getX()*width, list.get(j).getY()*height);
                    mCanvas.drawPath(mPath, mPaint);
                    //这里来控制暂停和继续
                    while(suspended) {
                    }
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                //每隔0.05秒刷新一次
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            mIsDrawing = false;

            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    };

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            canvas=mHolder.lockCanvas();
            canvas.drawColor(Color.WHITE);
            if (mPath != null) {
                // 实时的显示
                canvas.drawPath(mPath, mPaint);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            if (canvas!=null) {
                // 将前面已经画过得显示出来
                canvas.drawBitmap(mBitmap, 0, 0, mPaint);
                mHolder.unlockCanvasAndPost(canvas);// 绘制后解锁，绘制后必须解锁才能显示

            }
        }
    };

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    handler.removeCallbacks(runnable);
                    break;

                default:
                    break;
            }
        }
    };
    public String readTxtFile(String fileName)throws IOException {
        //得到文件路径
        String path = GloableParams.localFile;
        //创建文件
        File dir = new File(path);
        if (!dir.exists()){
            return "找不到该路径";
        }
        File file = new File(dir,fileName);
        String res = null;

        FileInputStream input = new FileInputStream(file);
        int length = input.available();
        byte [] buffer = new byte[length];
        input.read(buffer);
        res = EncodingUtils.getString(buffer, "UTF-8");
        input.close();
        //解析
        return res;
    }

    public void onDestory() {
        mIsDrawing = false;
        handler.removeCallbacks(runnable);
    }
    int width;
    int height;
    private void initCanvas() {
        mHolder=getHolder();
        mHolder.addCallback(this);
        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setKeepScreenOn(true);

        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        //保存之前画的数据
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mBitmap.eraseColor(Color.argb(0, 0, 0, 0));
        mCanvas = new Canvas(mBitmap);  //所有mCanvas画的东西都被保存在了mBitmap中
        mCanvas.drawColor(Color.TRANSPARENT);
    }

    private static final float TOUCH_TOLERANCE = 4;
    private float mX, mY;// 临时点坐标
    private void touch_start(float x, float y) {
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    /**
     * 贝塞尔曲线
     * @param x
     * @param y
     */
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(mY - y);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }
}
